package com.ty.superapi.service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ty.superapi.dao.UserDao;
import com.ty.superapi.entity.User;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import com.xiaoleilu.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.xiaoleilu.hutool.crypto.symmetric.SymmetricCrypto;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.CharsetUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianyu
 * @since 2017-12-21
 */
@Service
public class UserService extends ServiceImpl<UserDao, User> {
    // aes加密密钥-暂时不包含权限处理
    private String key = "tianyu1234567890";

    /**
     * 新增或修改用户
     *
     * @param user
     * @return
     */
    public boolean put(User user) {
        if (StringUtils.isEmpty(user.getId())) {
            String pwd = SecureUtil.md5(user.getPassword());
            user.setPassword(pwd);
            user.setCreateDate(DateUtil.date());
        }
        return insertOrUpdate(user);
    }

    /**
     * token加密
     *
     * @param content
     * @return
     */
    public String encryptToken(String content) {
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
        return aes.encryptHex(content);
    }

    /**
     * token解密
     *
     * @param token
     * @return
     */
    public String decryptToken(String token) {
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
        return aes.decryptStr(token, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 从token中解密出用户id
     *
     * @param token
     * @return
     */
    public Integer getIdFromToken(String token) {
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
        String str = aes.decryptStr(token, CharsetUtil.CHARSET_UTF_8);
        return Integer.valueOf(str.split("&")[0]);
    }

}
